<script>
import {h, inject, nextTick, onBeforeUnmount, onMounted, watch} from 'vue';
import {Modal} from 'ant-design-vue';

import useDrag from "./useDrag";

const DEFAULT_PERCENT_HUNDRED = 'calc( 100vh - 214px )';
const DEFAULT_VIEW_HUNDRED = 'calc( 100vh - 111px )';

const DEFAULT_DIALOG_CONTAINER = 'dialogContainer';

/**
 * 进一步封装Antdv的Modal组件，扩展常用属性
 */
export default {
  name: 'SagDialog',
  props: {
    height: { type: [Number, String], default: '' },
    visible: {
      type: Boolean,
      default: false,
    },
    mountainTop: {
      // 是否在顶层挂载
      type: Boolean,
      default: true,
    },
    maskClosable: {
      type: Boolean,
      default: false
    }
  },
  setup(props, ctx) {

    const { attrs, slots } = ctx;

    const getDialogContainer = props.mountainTop ? (() => document.body) : inject(DEFAULT_DIALOG_CONTAINER);

    const defaultHeight = props.mountainTop?DEFAULT_VIEW_HUNDRED:DEFAULT_PERCENT_HUNDRED;

    // 拖拽功能
    const className = Math.random().toString(36).substring(2);
    const {initialEvent, resetNum, removeUp, removeMove,} = useDrag(className);

    watch(()=>props.visible, val => {
      if(!val){
        resetNum();
      }
      nextTick(()=>{
        initialEvent(val);
      });
    });

    onMounted(()=>{
      nextTick(()=>{
        initialEvent(props.visible);
      });
    });

    onBeforeUnmount(()=>{
      removeMove()
      window.removeEventListener('mouseup', removeUp, false);
    });

    return () =>
      h(
        Modal,
        {
          ...attrs,
          centered: true,
          destroyOnClose: true,
          keyboard: false,
          visible: props.visible,
          maskClosable: props.maskClosable,
          bodyStyle: {
            overflowY: 'auto',
            minHeight: '300px',
            height: props.height === '100%'?defaultHeight:props.height,
            maxHeight: props.height === '100%'?'initial':defaultHeight,
          },
          okText: '确定',
          cancelText: '取消',
          wrapClassName: 'sag-dialog-wrap',
          getContainer: getDialogContainer,
          class: [
            className
          ]
        },
        { ...slots }
      );
  },
};
</script>

<style>
.ant-modal div[aria-hidden="true"]{
  display: none !important;
}
</style>
